package com.wangan;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.layout.font.FontProvider;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) {
        // 获取 java 版本
        String version = System.getProperty("java.specification.version");

        // 获取系统类型
        String platform = System.getProperty("os.name", "");
        platform = platform.toLowerCase().contains("window") ? "win" : "linux";

        // 当前程序目录
        String current = System.getProperty("user.dir");

        System.out.println(String.format("current=%s", current));

        // html 文件路径
        File index = Paths.get(current, "..", "index.html").toFile();
        if (!index.exists()) {
            System.out.println(String.format("file not exist,file=%s", index.getAbsolutePath()));
            return;
        }

        try {
            // 保存 pdf 文件路径
            File file = Paths.get(current, String.format("java%s_%s.pdf", version, platform)).toFile();

            // 转换设置
            ConverterProperties options = new ConverterProperties();

            // 设置根目录类型
            String baseUri = Paths.get(current, "..").toUri().toString();
            options.setBaseUri(baseUri);

            // 设置字体
            FontProvider fontProvider = new FontProvider();
            fontProvider.addStandardPdfFonts();
            fontProvider.addSystemFonts();
            options.setFontProvider(fontProvider);

            // 转换 html 文件
            HtmlConverter.convertToPdf(index, file, options);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}